package com.instreet.idra.dao.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.instreet.idra.dao.IGameDao;
import com.instreet.idra.model.Game;

public class GameDaoImpl implements IGameDao{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
		this.jdbcTemplate=jdbcTemplate;
	}

	@Override
	public void saveOrUpdate(Game game) {
		if (game.getId() > 0) {
	        // update
	        String sql = "UPDATE game SET title=?,createDate=? WHERE id=?";
	        jdbcTemplate.update(sql,game.getTitle(),game.getCreateDate() );
	    } else {
	        // insert
	        String sql = "INSERT INTO game (title,createDate) VALUES (?, ?)";
	        jdbcTemplate.update(sql, game.getTitle(),game.getCreateDate());
	    }
	}

	@Override
	public void delete(Long id) {
		String sql = "DELETE FROM contact WHERE contact_id=?";
	    jdbcTemplate.update(sql, id);
	}

	@Override
	public List<Game> list() {
		String sql = "SELECT * FROM game";
	    List<Game> listGame = jdbcTemplate.query(sql, new RowMapper<Game>() {
	 
	        @Override
	        public Game mapRow(ResultSet rs, int rowNum) throws SQLException {
	            Game g = new Game();
	            g.setId(rs.getLong("id"));
	            g.setTitle(rs.getString("title"));
	            g.setCreateDate(rs.getDate("createDate"));
	            return g;
	        }
	    });
	    return listGame;
	}

	@Override
	public Game select(Long id) {
		String sql = "SELECT * FROM game WHERE id=" + id;
	    return jdbcTemplate.query(sql, new ResultSetExtractor<Game>() {
	 
	        @Override
	        public Game extractData(ResultSet rs) throws SQLException,
	                DataAccessException {
	            if (rs.next()) {
	            	Game g = new Game();
	            	g.setId(rs.getLong("id"));
		            g.setTitle(rs.getString("title"));
		            g.setCreateDate(rs.getDate("createDate"));
		            return g;
	            }
	            return null;
	        }
	    });
	}
}
